<script lang="ts" setup>
import { type CommentVO, getCommentPageApi } from '@/request/api/comment'
import { initPageVO, type PageDTO, type PageVO, type ResultType } from '@/type/type'
import { useUserStore } from '@/stores/user'
import { useSocketStore } from '@/stores/socket'
import { useScrollStore } from '@/stores/scroll'
import { useSystemStore } from '@/stores/system'
import { Code } from '@/request/code'
import { fromNow } from '@/utils/timeUtils'
import { useTemporaryStore } from '@/stores/temporary'
import { isEmpty } from '@/utils'
import { updateLikeApi } from '@/request/api/like'

const userStore = useUserStore()
const systemStore = useSystemStore()
const socketStore = useSocketStore()
const scrollStore = useScrollStore()
const temporaryStore = useTemporaryStore()

const { id } = defineProps({
  id: {
    type: Number,
    default: undefined
  }
})

const page = reactive<PageDTO>({
  size: 10,
  current: 0,
  param: {}
})

const pageVO = reactive<PageVO<CommentVO>>(initPageVO())

const getList = () => {
  page.current++
  page.param.sourceId = id
  getCommentPageApi(page).then((res: ResultType<PageVO<CommentVO>>) => {
    if (res.code === Code.SUCCESS && res.data.list.length > 0) {
      pageVO.list.push(...res.data.list)
      pageVO.isEmpty = res.data.isEmpty
    }
  })
}

onMounted(() => {
  getList()
  // 初始化 评论源id
  temporaryStore.comment.sourceId = id
  socketStore.initCommentSocket((res: CommentVO) => {
    // 判断接收到的评论 sourceId 是不是 id 或者是 留言的评论
    if ((id != undefined && res.sourceId === id) || (id == undefined && res.sourceId === res.id)) {
      if (res.floorId === res.id) {
        // 添加到 list 中, list为[] 时用 push, 否则用unshift
        if (pageVO.list.length === 0) {
          pageVO.list.push(res)
        } else {
          pageVO.list.unshift(res)
        }
      } else {
        for (let i = 0; i < pageVO.list.length; i++) {
          if (res.floorId === pageVO.list[i].id) {
            if (isEmpty(pageVO.list[i].children)) {
              pageVO.list[i].children = []
            }
            pageVO.list[i].children.push(res)
          }
        }
      }
    }
  })
})

const reply = (item: CommentVO) => {
  temporaryStore.comment.floorId = item.floorId
  temporaryStore.comment.userId = userStore.user.id
  temporaryStore.comment.parentUserId = item.user.id
  temporaryStore.commentReply.parentName = item.user.username
  temporaryStore.commentReply.isReply = true
}

watch(
  () => scrollStore.scroll.isBottom,
  (val) => {
    if (val && !pageVO.isEmpty) {
      const timeout = setTimeout(() => {
        getList()
        clearTimeout(timeout)
      }, 500)
    }
  }
)
</script>

<template>
  <div class="flex w-full flex-col">
    <el-affix :offset="0" class="w-full" position="top">
      <Editor class="z-20" />
    </el-affix>
    <el-empty v-if="pageVO.list.length === 0" description="还没有评论呢！" />
    <el-container
      v-else
      class="use-second-bg use-transitions-colors z-10 py-5"
      direction="vertical"
    >
      <el-container v-for="p in pageVO.list" :key="p.id" class="p-5 gap-1" direction="vertical">
        <el-container class="gap-2 items-center">
          <el-avatar :size="50" :src="p.user.avatar" alt="" class="min-w-12" />
          <el-container class="gap-1 w-full justify-between">
            <el-container class="gap-1" direction="vertical">
              <el-container class="items-center text-amber-500 ellipsis-1">
                <span>{{ p.user.username }}</span>
                <span class="text-sm text-teal-300">【{{ p.user.role.name }}】</span>
              </el-container>
              <span class="text-sm ellipsis-1 text-gray-500">{{ fromNow(p.createTime) }}</span>
            </el-container>
            <span class="flex items-center gap-2">
              <a
                class="border flex items-center justify-center h-fit py-0.5 px-1 min-w-10 text-center text-xs use-radius-xs use-transitions-shadow-short use-hover-color"
                href="javascript:"
                @click="updateLikeApi(p.id)"
              >
                点赞{{ p.likeCount }}
              </a>
              <a
                class="border flex items-center justify-center h-fit py-0.5 px-1 min-w-10 text-center text-xs use-radius-xs use-transitions-shadow-short use-hover-color"
                href="javascript:"
                @click="reply(p)"
              >
                回复{{ p.children?.length }}
              </a>
            </span>
          </el-container>
        </el-container>
        <el-container class="pl-14 gap-5 max-sm:pl-5" direction="vertical">
          <el-container
            class="use-third-bg p-3 gap-2 use-radius-sm use-transitions-shadow-short"
            direction="vertical"
          >
            <template v-if="p.content">
              <span class="w-full whitespace-pre-wrap break-words">{{ p.content }}</span>
            </template>
            <template v-if="p.imgUrl">
              <a class="w-fit" href="javascript:">
                <img
                  :src="p.imgUrl"
                  alt="图片"
                  class="max-h-52 use-radius-sm use-transitions-shadow-short"
                  @click="systemStore.imgPreview.imgUrl = p.imgUrl"
                />
              </a>
            </template>
          </el-container>
          <el-container
            v-for="item in p.children"
            :key="item.id"
            class="gap-1"
            direction="vertical"
          >
            <el-container class="gap-2 items-center">
              <el-avatar :size="50" :src="p.user.avatar" class="min-w-12" />
              <el-container class="w-full justify-between">
                <el-container class="gap-1" direction="vertical">
                  <el-container class="items-center text-amber-500 ellipsis-1">
                    <span>{{ item.user.username }}</span>
                    <span class="text-sm text-teal-300">【{{ item.user.role.name }}】</span>
                  </el-container>
                  <span class="text-sm ellipsis-1 text-gray-500">
                    {{ fromNow(item.createTime) }}
                  </span>
                </el-container>
                <span class="flex items-center gap-2">
                  <a
                    class="border flex items-center justify-center h-fit py-0.5 px-1 min-w-10 text-center text-xs use-radius-xs use-transitions-shadow-short use-hover-color"
                    href="javascript:"
                    @click="updateLikeApi(p.id)"
                  >
                    点赞{{ item.likeCount }}
                  </a>
                  <a
                    class="border flex items-center justify-center h-fit py-0.5 px-1 min-w-10 text-center text-xs use-radius-xs use-transitions-shadow-short use-hover-color"
                    href="javascript:"
                    @click="reply(item)"
                  >
                    回复
                  </a>
                </span>
              </el-container>
            </el-container>
            <el-container class="pl-14 max-sm:pl-5">
              <el-container
                :class="
                  'w-full gap-2 use-radius-sm use-transitions-shadow-short ' +
                  (item.imgUrl ? 'flex-col' : '')
                "
              >
                <span v-if="item.parentUser.id != item.user.id" class="text-amber-500"
                  >@{{ item.parentUser.username }}</span
                >
                <el-container
                  class="use-third-bg p-3 gap-2 w-full use-radius-sm use-transitions-colors-short"
                  direction="vertical"
                >
                  <template v-if="item.content">
                    <span class="whitespace-pre-wrap break-words">{{ item.content }}</span>
                  </template>
                  <template v-if="item.imgUrl">
                    <a class="w-fit" href="javascript:">
                      <img
                        :src="item.imgUrl"
                        alt="图片"
                        class="max-h-52 use-radius-sm use-transitions-shadow-short"
                        @click="systemStore.imgPreview.imgUrl = item.imgUrl"
                      />
                    </a>
                  </template>
                </el-container>
              </el-container>
            </el-container>
          </el-container>
        </el-container>
        <hr class="w-full mt-5 bg-gray-300" />
      </el-container>
      <el-container class="justify-center p-5">
        <SvgIcon
          v-if="!pageVO.isEmpty"
          message="加载中..."
          name="refresh"
          svg-class="animate-spin !size-5 duration-1000"
        />
        <el-empty v-else class="z-20" description="没有更多评论了！" />
      </el-container>
    </el-container>
  </div>
</template>

<style lang="scss" scoped></style>
